<template>
  <view class="expansion-edit-container">
    <u-navbar
      :title="isEdit ? '编辑信息化拓展' : '新增信息化拓展'"
      :border-bottom="true"
      back-icon-color="#007aff"
      back-text="返回"
      :back-text-style="{color: '#007aff'}"
      :auto-back="true"
    ></u-navbar>

    <view class="cu-card case shadow">
      <view class="cu-item shadow">
        <view class="company-info">
          <view class="text-xxl text-bold text-black padding-sm">{{ groupInfo.name }}</view>
          <view class="padding-xs flex">
            <view
              class="cu-tag bg-blue light radius margin-right-xs"
              v-if="groupInfo.industry"
            >{{ groupInfo.industry }}</view>
            <view
              class="cu-tag bg-blue light radius"
              v-if="groupInfo.district"
            >{{ groupInfo.district }}</view>
          </view>
        </view>

        <view class="cu-form-group">
          <view class="title">
            <text class="text-red">*</text>产品类别
          </view>
          <picker
            @change="onCategoryChange"
            :value="categoryIndex"
            :range="categoryList"
            range-key="label"
          >
            <view class="picker">{{ form.categoryName || '请选择产品类别' }}</view>
          </picker>
        </view>

        <view class="cu-form-group">
          <view class="title">
            <text class="text-red">*</text>拟拓展产品
          </view>
          <picker
            @change="onProductChange"
            :value="productIndex"
            :range="currentProductList"
            range-key="label"
            :disabled="!form.category"
          >
            <view class="picker">{{ form.productName || '请选择拟拓展产品' }}</view>
          </picker>
        </view>

        <view class="cu-form-group">
          <view class="title">
            <text class="text-red">*</text>产品数量
          </view>
          <input v-model="form.quantity" type="number" placeholder="请输入数量" class="radius" />
        </view>

        <view class="cu-form-group">
          <view class="title">
            <text class="text-red">*</text>预计金额(元/年)
          </view>
          <input v-model="form.amount" type="number" placeholder="请输入金额" class="radius" />
        </view>

        <view class="cu-form-group">
          <view class="title">
            <text class="text-red">*</text>预计落地时间
          </view>
          <picker mode="date" :value="form.expectedTime" @change="onDateChange">
            <view class="picker">{{ form.expectedTime || '请选择时间' }}</view>
          </picker>
        </view>

        <view class="cu-form-group">
          <view class="title">项目/服务包</view>
          <switch class="blue" :checked="form.isProject" @change="switchChange"></switch>
          <text class="margin-left-xs">{{ form.isProject ? '是' : '否' }}</text>
        </view>

        <view class="cu-form-group" v-if="isEdit">
          <view class="title">是否已落地</view>
          <switch class="blue" :checked="form.isLanded" @change="landedChange"></switch>
          <text class="margin-left-xs">{{ form.isLanded ? '是' : '否' }}</text>
        </view>

        <view class="cu-form-group" v-if="isEdit">
          <view class="title">商机状态</view>
          <picker
            @change="onStatusChange"
            :value="statusIndex"
            :range="statusList"
            range-key="label"
          >
            <view class="picker">
              <view :class="'cu-tag radius ' + getStatusClass()">{{ form.statusText || '请选择状态' }}</view>
            </view>
          </picker>
        </view>

        <view class="policy-form-group">
          <view class="policy-title">投放政策及资费</view>
          <textarea
            v-model="form.policy"
            placeholder="请输入投放政策及资费详情..."
            maxlength="-1"
            class="policy-textarea"
          ></textarea>
        </view>

        <view class="padding-sm flex flex-direction">
          <view class="flex align-center justify-between margin-bottom">
            <view class="manager-info" v-if="form.category">
              <text class="text-grey margin-right-xs">产品主管：</text>
              <text class="text-black">{{ managerMap[form.category] }}</text>
            </view>
          </view>

          <view class="flex justify-end">
            <button class="cu-btn bg-blue margin-right" @click="saveExpansion">保存</button>
            <button class="cu-btn line-blue" @click="goBack">取消</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      groupCode: "",
      expansionId: "",
      isEdit: false,
      groupInfo: {},
      form: {
        category: "",
        categoryName: "",
        product: "",
        productName: "",
        quantity: "",
        amount: "",
        expectedTime: "",
        policy: "",
        isProject: false,
        isLanded: false,
        status: "progress",
        statusText: "跟进中"
      },
      // 索引值
      categoryIndex: 0,
      productIndex: 0,
      statusIndex: 0,
      // 选项列表
      categoryList: [
        { label: "专线", value: "专线" },
        { label: "移动云", value: "移动云" },
        { label: "物联网", value: "物联网" },
        { label: "短彩信", value: "短彩信" },
        { label: "其他", value: "其他" }
      ],
      productOptions: {
        专线: [
          { label: "互联网专线", value: "互联网专线" },
          { label: "数据专线", value: "数据专线" },
          { label: "商务快线 AB", value: "商务快线 AB" },
          { label: "商务快线 C", value: "商务快线 C" },
          { label: "VPN专线", value: "VPN专线" },
          { label: "政务外网", value: "政务外网" },
          { label: "专线卫士", value: "专线卫士" },
          { label: "FTTR-B", value: "FTTR-B" },
          { label: "E企组网(路由器)", value: "E企组网(路由器)" },
          { label: "企业宽带", value: "企业宽带" },
          { label: "其它", value: "其它" }
        ],
        移动云: [
          { label: "云电脑", value: "云电脑" },
          { label: "云主机类", value: "云主机类" },
          { label: "saas类", value: "saas类" }
        ],
        物联网: [
          { label: "物联网卡", value: "物联网卡" },
          { label: "千里眼", value: "千里眼" },
          { label: "和对讲", value: "和对讲" },
          { label: "5G CPE", value: "5G CPE" },
          { label: "烟感", value: "烟感" }
        ],
        短彩信: [{ label: "云MAS", value: "云MAS" }],
        其他: [
          { label: "IDC", value: "IDC" },
          { label: "和教育", value: "和教育" },
          { label: "其他", value: "其他" }
        ]
      },
      statusList: [
        { label: "跟进中", value: "跟进中" },
        { label: "已落地", value: "已落地" },
        { label: "已废弃", value: "已废弃" }
      ],
      managerMap: {
        专线: "李晶晶",
        移动云: "周凌峰",
        物联网: "石慧贤",
        短彩信: "乔花",
        其他: "暂无"
      }
    };
  },
  computed: {
    currentProductList() {
      if (!this.form.category) return [];
      return this.productOptions[this.form.category] || [];
    }
  },
  onLoad(options) {
    console.log("拓展编辑页面收到的参数:", options);

    // 获取groupCode
    if (options.groupCode) {
      this.groupCode = options.groupCode;
      this.getGroupInfo();
    } else {
      uni.showToast({
        title: "缺少集团单位编码",
        icon: "none"
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }

    // 获取expansionId
    if (options.expansionId) {
      this.expansionId = options.expansionId;
      this.isEdit = true;
      this.getExpansionDetail();
    }
  },
  methods: {
    // 获取集团单位信息
    getGroupInfo() {
      console.log("开始获取集团信息，groupCode:", this.groupCode);

      // 显示加载提示
      uni.showLoading({
        title: "加载中..."
      });

      // 调用接口获取集团信息
      this.$http
        .sendRequest("zhanke/group_detail", "POST", {
          groupCode: this.groupCode
        })
        .then(res => {
          uni.hideLoading();
          console.log("集团信息API返回:", res.data);

          if (res.data && res.data.code === 200) {
            // 设置集团信息
            const detail = res.data.data;
            this.groupInfo = {
              name: detail.name,
              code: detail.code,
              district: detail.district,
              industry: detail.industry,
              industryCode: detail.industryCode,
              industryChain: detail.industryChain,
              manager: detail.manager
            };
            console.log("集团信息获取成功:", this.groupInfo);
          } else {
            // 请求失败处理
            console.error("获取集团信息失败:", res.data.msg);
            uni.showToast({
              title: res.data.msg || "获取集团信息失败",
              icon: "none"
            });
            // 获取不到数据时使用本地默认数据
            this.getGroupInfoFromStorage();
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error("获取集团信息出错:", err);
          // 请求出错，使用本地数据
          this.getGroupInfoFromStorage();
          uni.showToast({
            title: "网络请求失败，显示本地数据",
            icon: "none"
          });
        });
    },

    // 从本地存储获取集团信息
    getGroupInfoFromStorage() {
      try {
        const storageData = uni.getStorageSync("groupInfo_" + this.groupCode);
        if (storageData) {
          this.groupInfo = JSON.parse(storageData);
        } else {
          // 本地无数据时使用默认数据
          this.groupInfo = {
            name: "未知集团单位",
            code: this.groupCode,
            district: "未知",
            industry: "未知",
            industryCode: "",
            industryChain: "",
            manager: ""
          };
        }
      } catch (e) {
        console.error("读取本地存储出错:", e);
        this.groupInfo = {
          name: "未知集团单位",
          code: this.groupCode,
          district: "未知",
          industry: "未知"
        };
      }
    },

    // 获取拓展项详情
    getExpansionDetail() {
      console.log("开始获取拓展详情，expansionId:", this.expansionId);

      // 显示加载提示
      uni.showLoading({
        title: "加载中..."
      });

      // 模拟一个详情接口（实际开发时应替换为真实接口）
      // 参考API文档，可以使用expansion_list接口带id过滤条件获取单条记录
      this.$http
        .sendRequest("zhanke/expansion_list", "POST", {
          groupCode: this.groupCode,
          expansionId: this.expansionId
        })
        .then(res => {
          uni.hideLoading();
          console.log("拓展详情API返回:", res.data);

          if (
            res.data &&
            res.data.code === 200 &&
            res.data.data.list &&
            res.data.data.list.length > 0
          ) {
            // 获取第一条记录
            const detail = res.data.data.list[0];

            // 状态对应（不再需要映射，直接使用后端返回的状态文本）
            this.form = {
              category: detail.category || "其他",
              categoryName: this.getCategoryName(detail.category),
              product: detail.product || "",
              productName: detail.productName || "",
              quantity: detail.quantity?.toString() || "",
              amount: detail.estimatedAmount?.toString() || "",
              expectedTime: detail.expectedLandingDate || "",
              policy: detail.policyRate || "",
              isProject: detail.isProject || false,
              isLanded: detail.isLanded || false,
              status: detail.status || "跟进中",
              statusText: detail.status || "跟进中"
            };

            console.log("拓展详情获取成功，设置表单:", this.form);

            // 设置选择器初始索引
            this.setCategoryIndex();
            this.setProductIndex();
            this.setStatusIndex();
          } else {
            console.error("获取拓展详情失败:", res.data.msg);
            uni.showToast({
              title: res.data.msg || "获取拓展详情失败",
              icon: "none"
            });
            // 数据获取失败，返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error("获取拓展详情出错:", err);
          uni.showToast({
            title: "网络请求失败",
            icon: "none"
          });
          // 数据获取失败，返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        });
    },

    // 获取类别名称
    getCategoryName(categoryValue) {
      // 由于现在value和label值相同，直接返回categoryValue即可
      // 如果没有值，则返回"其他"
      return categoryValue || "其他";
    },

    // 设置类别索引
    setCategoryIndex() {
      this.categoryIndex = this.categoryList.findIndex(
        item => item.value === this.form.category
      );
      if (this.categoryIndex === -1) {
        this.categoryIndex = 0;
      }
    },

    // 设置产品索引
    setProductIndex() {
      if (this.currentProductList.length > 0) {
        this.productIndex = this.currentProductList.findIndex(
          item => item.value === this.form.product
        );
        if (this.productIndex === -1) {
          this.productIndex = 0;
        }
      }
    },

    // 设置状态索引
    setStatusIndex() {
      this.statusIndex = this.statusList.findIndex(
        item => item.value === this.form.status
      );
      if (this.statusIndex === -1) {
        this.statusIndex = 0;
      }
    },

    // 选择产品类别
    onCategoryChange(e) {
      const index = e.detail.value;
      const item = this.categoryList[index];
      this.categoryIndex = index;
      this.form.category = item.value;
      this.form.categoryName = item.label;
      // 清空产品选择
      this.form.product = "";
      this.form.productName = "";
      this.productIndex = 0;
    },

    // 选择产品
    onProductChange(e) {
      const index = e.detail.value;
      const item = this.currentProductList[index];
      this.productIndex = index;
      this.form.product = item.value;
      this.form.productName = item.label;
    },

    // 选择日期
    onDateChange(e) {
      this.form.expectedTime = e.detail.value;
    },

    // 选择商机状态
    onStatusChange(e) {
      const index = e.detail.value;
      const item = this.statusList[index];
      this.statusIndex = index;
      this.form.status = item.value;
      this.form.statusText = item.label;

      // 自动设置落地状态
      if (item.value === "已落地") {
        this.form.isLanded = true;
      }
    },

    // 项目/服务包开关
    switchChange(e) {
      this.form.isProject = e.detail.value;
    },

    // 是否已落地开关
    landedChange(e) {
      this.form.isLanded = e.detail.value;
    },

    // 获取状态样式类
    getStatusClass() {
      if (this.form.status === "跟进中") return "bg-blue light";
      if (this.form.status === "已落地") return "bg-green light";
      if (this.form.status === "已废弃") return "bg-red light";
      return "bg-grey light";
    },

    // 保存
    saveExpansion() {
      // 表单验证
      if (!this.form.category) {
        uni.showToast({
          title: "请选择产品类别",
          icon: "none"
        });
        return;
      }

      if (!this.form.productName) {
        uni.showToast({
          title: "请选择拟拓展产品",
          icon: "none"
        });
        return;
      }

      if (!this.form.quantity) {
        uni.showToast({
          title: "请输入产品数量",
          icon: "none"
        });
        return;
      }

      if (!this.form.amount) {
        uni.showToast({
          title: "请输入预计金额",
          icon: "none"
        });
        return;
      }

      if (!this.form.expectedTime) {
        uni.showToast({
          title: "请选择预计落地时间",
          icon: "none"
        });
        return;
      }

      // 显示加载
      uni.showLoading({
        title: "保存中...",
        mask: true
      });

      // 构造API请求参数
      const params = {
        groupCode: this.groupCode,
        productName: this.form.productName,
        category: this.form.category,
        quantity: parseInt(this.form.quantity) || 0,
        estimatedAmount: parseFloat(this.form.amount) || 0,
        expectedLandingDate: this.form.expectedTime,
        policyRate: this.form.policy,
        isProject: this.form.isProject
      };

      // 编辑模式需要添加ID和状态
      if (this.isEdit) {
        params.id = this.expansionId;
        params.status = this.form.statusText; // 使用中文状态名称
        params.isLanded = this.form.isLanded;
      }

      console.log("准备保存的数据:", params);

      // 调用API
      const apiUrl = this.isEdit
        ? "zhanke/expansion_update"
        : "zhanke/expansion_add";

      this.$http
        .sendRequest(apiUrl, "POST", params)
        .then(res => {
          uni.hideLoading();
          console.log("保存结果:", res.data);

          if (res.data && res.data.code === 200) {
            uni.showToast({
              title: this.isEdit ? "编辑成功" : "新增成功",
              icon: "success"
            });

            // 返回上一页
            setTimeout(() => {
              this.goBack();
            }, 1500);
          } else {
            uni.showToast({
              title: res.data.msg || "保存失败，请重试",
              icon: "none"
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error("保存出错:", err);
          uni.showToast({
            title: "网络请求失败，请重试",
            icon: "none"
          });
        });
    },

    // 返回上一页
    goBack() {
      uni.navigateBack();
    }
  }
};
</script>

<style>
.expansion-edit-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 30px;
}

.cu-card.case {
  margin: 15px;
  margin-top: 90px; /* 添加顶部边距，避免被导航栏遮挡 */
  overflow: hidden;
}

.company-info {
  padding: 10rpx 20rpx;
  border-bottom: 1rpx solid #eee;
}

.cu-form-group {
  min-height: 100rpx;
  align-items: center;
}

.cu-form-group .title {
  min-width: 200rpx;
  padding-right: 20rpx;
}

.picker {
  text-align: right;
  color: #555;
  flex: 1;
}

input {
  text-align: right;
  color: #555;
}

.policy-form-group {
  margin-top: 20rpx;
  margin-bottom: 20rpx;
  padding: 20rpx 30rpx;
  background-color: #fff;
}

.policy-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.policy-textarea {
  height: 200rpx;
  min-height: 200rpx;
  width: 100%;
  background-color: #f8f9fc;
  border-radius: 8rpx;
  padding: 20rpx;
  text-align: left;
  border: 1rpx solid #eee;
}

.manager-info {
  padding: 10rpx 0;
  display: flex;
  align-items: center;
}
</style> 